<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <title>远程语音播控</title>
  <style>
    body { font-family: Arial, sans-serif; text-align: center; margin-top: 100px; }
    button { padding: 10px 20px; font-size: 18px; margin: 5px; }
    #log { margin-top: 20px; font-size: 20px; color: green; }
    #debug { margin-top: 20px; font-size: 14px; color: gray; text-align: left; max-width: 600px; margin-left: auto; margin-right: auto; background: #f5f5f5; padding: 10px; border-radius: 5px; max-height: 300px; overflow-y: auto; }
    .settings { margin-top: 20px; padding: 15px; border: 1px solid #ddd; border-radius: 5px; display: inline-block; }
    input { padding: 5px; margin: 5px; }
    label { margin-right: 10px; }
  </style>
</head>
<body>
  <h1>远程语音播控</h1>
  
  <div class="settings">
    <h3>设置</h3>
    <div>
      <label for="targetUrl">目标URL:</label>
      <input type="text" id="targetUrl" value="http://192.168.0.111:5000/signal" size="40">
    </div>
    <div>
      <label for="useProxy">使用代理:</label>
      <input type="checkbox" id="useProxy">
    </div>
    <div>
      <label for="proxyUrl">代理URL:</label>
      <input type="text" id="proxyUrl" value="http://localhost:8080/proxy" size="40">
    </div>
  </div>
  
  <button id="startBtn">开始监听</button>
  <button id="stopBtn">停止监听</button>
  <button id="testBtn">测试连接</button>
  
  <div id="log">未开始</div>
  <div id="debug">调试信息将显示在这里</div>

  <script>
    const log = document.getElementById("log");
    const debug = document.getElementById("debug");
    const startBtn = document.getElementById("startBtn");
    const stopBtn = document.getElementById("stopBtn");
    const testBtn = document.getElementById("testBtn");
    const targetUrlInput = document.getElementById("targetUrl");
    const useProxyCheckbox = document.getElementById("useProxy");
    const proxyUrlInput = document.getElementById("proxyUrl");

    // 添加调试日志函数
    function addDebugLog(message) {
      const now = new Date().toLocaleTimeString();
      debug.innerHTML += `[${now}] ${message}<br>`;
      debug.scrollTop = debug.scrollHeight; // 自动滚动到底部
      console.log(`[DEBUG] ${message}`);
    }

    // 清空调试日志
    function clearDebugLog() {
      debug.innerHTML = "";
    }

    // 获取实际发送请求的URL
    function getRequestUrl() {
      const targetUrl = targetUrlInput.value.trim();
      if (useProxyCheckbox.checked) {
        const proxyUrl = proxyUrlInput.value.trim();
        // 提取目标URL的路径部分
        const targetPath = targetUrl.replace(/^https?:\/\/[^\/]+/, '');
        return proxyUrl + targetPath;
      }
      return targetUrl;
    }

    // 测试连接函数
    function testConnection() {
      clearDebugLog();
      addDebugLog("开始测试连接...");
      
      const url = getRequestUrl();
      addDebugLog(`测试URL: ${url}`);
      addDebugLog(`使用代理: ${useProxyCheckbox.checked}`);
      
      // 发送测试请求
      fetch(url, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ value: 999, test: true })
      })
      .then(res => {
        addDebugLog(`请求成功发送，状态码: ${res.status}`);
        addDebugLog(`状态文本: ${res.statusText}`);
        
        // 显示响应头
        const headers = {};
        res.headers.forEach((value, key) => {
          headers[key] = value;
        });
        addDebugLog("响应头信息:");
        addDebugLog(JSON.stringify(headers, null, 2));
        
        return res.text();
      })
      .then(data => {
        addDebugLog(`服务器响应: ${data}`);
        addDebugLog("✅ 连接测试完成");
      })
      .catch(error => {
        addDebugLog(`❌ 请求失败: ${error.message}`);
        addDebugLog("可能的解决方法:");
        addDebugLog("1. 确保目标服务器正在运行");
        addDebugLog("2. 检查IP地址和端口是否正确");
        addDebugLog("3. 尝试启用代理选项");
        addDebugLog("4. 运行cors_proxy.py作为代理服务器");
      });
    }

    let recognition;
    if ('webkitSpeechRecognition' in window) {
      recognition = new webkitSpeechRecognition();
      addDebugLog("使用webkitSpeechRecognition");
    } else if ('SpeechRecognition' in window) {
      recognition = new SpeechRecognition();
      addDebugLog("使用SpeechRecognition");
    } else {
      addDebugLog("你的浏览器不支持语音识别 API");
      log.innerText = "你的浏览器不支持语音识别 API";
    }

    if (recognition) {
      recognition.lang = "zh-CN";  // 语音识别中文
      recognition.continuous = true;
      recognition.interimResults = false;

      recognition.onresult = function(event) {
        let transcript = event.results[event.results.length - 1][0].transcript.trim();
        log.innerText = "识别到: " + transcript;
        addDebugLog(`识别结果: ${transcript}`);

        let number = null;
        if (transcript.includes("第一款")) {
          number = 1;
          addDebugLog("检测到关键词'第一款'，对应数字1");
        } else if (transcript.includes("第二款")) {
          number = 2;
          addDebugLog("检测到关键词'第二款'，对应数字2");
        } else if (transcript.includes("第三款")) {
          number = 3;
          addDebugLog("检测到关键词'第三款'，对应数字3");
        } else if (transcript.includes("第四款")) {
          number = 4;
          addDebugLog("检测到关键词'第四款'，对应数字4");
        } else {
          addDebugLog("未检测到关键词");
        }

        if (number) {
          const url = getRequestUrl();
          log.innerText = "发送数字: " + number;
          addDebugLog(`准备发送请求到 ${url}，数据: {"value": ${number}}`);
          addDebugLog(`使用代理: ${useProxyCheckbox.checked}`);
          
          fetch(url, {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ value: number })
          })
          .then(res => {
            addDebugLog(`请求成功发送，状态码: ${res.status}`);
            console.log("已发送", number);
            return res.text();
          })
          .then(data => {
            addDebugLog(`服务器响应: ${data}`);
          })
          .catch(error => {
            addDebugLog(`请求失败: ${error.message}`);
            console.error("请求错误:", error);
            addDebugLog("建议: 尝试启用代理选项并运行cors_proxy.py");
          });
        }
      };

      recognition.onerror = function(event) {
        log.innerText = "识别错误: " + event.error;
        addDebugLog(`识别错误: ${event.error}`);
      };

      recognition.onstart = function() {
        addDebugLog("语音识别已开始");
      };

      recognition.onend = function() {
        addDebugLog("语音识别已结束");
      };

      startBtn.onclick = () => { 
        clearDebugLog();
        recognition.start(); 
        log.innerText = "正在监听...";
        addDebugLog("开始监听按钮被点击");
      };
      
      stopBtn.onclick = () => { 
        recognition.stop(); 
        log.innerText = "已停止";
        addDebugLog("停止监听按钮被点击");
      };
      
      testBtn.onclick = () => {
        testConnection();
      };
    }
  </script>
</body>
</html>
